package cn.afactory.tygz.ui.base.fragments;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.afactory.tygz.R;
import cn.afactory.tygz.controller.MessageController;
import cn.afactory.tygz.db.DBManager;
import cn.afactory.tygz.model.PrivateUserInfo;
import cn.afactory.tygz.model.PrivateUserInfoList;
import cn.afactory.tygz.model.SnsUserInfoList;
import cn.afactory.tygz.model.SysMessageItemList;
import cn.afactory.tygz.ui.base.BaseFragment;
import cn.afactory.tygz.ui.base.adapter.MessageListAdapter;
import cn.afactory.tygz.ui.base.entity.MessageInfo;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshBase;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshListView;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.NaviUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;
import cn.afactory.tygz.ui.fragments.BaseTabFragment;

/**
 * 消息列表
 */
public class MessageFragment extends BaseTabFragment{
    private MessageListAdapter mAdapter;
    private List<PrivateUserInfo> mList = new ArrayList<>();
    private MessageController mController;
    @Override
    public View onCreateViewCustom(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fg_message_list, null);
        plistview = (PullToRefreshListView)view.findViewById(R.id.lv_message_list);
        mController = new MessageController(getActivity(),mUIHandler);
        loadData();
        setTitle("消息");
        getActivity().registerReceiver(mBR,new IntentFilter(SPUtils.BR_ACTION_SYNC_MESSAGE_OK));
        return view;
    }

    @Override
    public void onDestroy() {
        getActivity().unregisterReceiver(mBR);
        super.onDestroy();
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what){
            case MessageController.MSG_LOAD_PRIVATE_USER_LIST_OK:
                handleMsgList((PrivateUserInfoList) msg.obj);
                break;
            case MessageController.MSG_LOAD_PRIVATE_USER_LIST_KO:
                if (mAdapter.getCount() == 0) {
//                    hideErrorPage(-1);
//                    showErrorPage(msg.arg1, new View.OnClickListener() {
//
//                        @Override
//                        public void onClick(View v) {
//                            startLoadData(true);
//                        }
//                    });
                } else {
                    LocalUtils.showToast(mContext, (String)msg.obj);
                }
                break;
        }
        // 结束下拉刷新
        if (plistview.isRefreshing()) {
            plistview.onRefreshComplete();
        }
    }

    /**
     * 处理私信列表
     * @param t
     */
    private void handleMsgList(PrivateUserInfoList t){
        hideErrorPage(-1);
        if (t.value != null && t.value.size() >= 0) {
            try {
                mList.addAll(t.value);
                //是否显示置顶链接VIEW
                mAdapter.setData(mList);
                setListListener();

                if (plistview.isRefreshing()) {
                    plistview.onRefreshComplete();
                }
                plistview.setMode(PullToRefreshBase.Mode.DISABLED);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
//            if (mAdapter.getCount() == 0) {
//                showNullPage();
//            }
        }
    }

    private void loadData() {
        plistview.setMode(PullToRefreshBase.Mode.DISABLED);
        handleHeaderView();
        mList = DBManager.getInstance(getActivity()).getAllPrivateUsers();
        mAdapter = new MessageListAdapter(mContext, mList);
        plistview.setAdapter(mAdapter);

        plistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListView lv = plistview.getRefreshableView();
                if (position >= lv.getHeaderViewsCount()) {
                    position -= lv.getHeaderViewsCount();
                }
                NaviUtils.gotoMessageDetail(getActivity(),
                        mList.get(position).userId,
                        mList.get(position).nickName,
                        mList.get(position).userIcon);
            }
        });
    }

    private void setListListener(){
        plistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadData(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadData(false);
            }
        });

        plistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NaviUtils.gotoMessageDetail(getActivity(),
                        mList.get(position).userId,
                        mList.get(position).nickName,
                        mList.get(position).userIcon);
            }
        });
    }

    private void startLoadData(boolean cleanData){
        if(cleanData){
            mList.clear();
        }
        mController.doGetPrivateUserList(1, 1000, System.currentTimeMillis());
    }

    /**
     * 增加消息头
     */
    private void handleHeaderView(){
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fg_message_list_item,null);
        ImageView messageIcon = (ImageView)view.findViewById(R.id.message_icon);
        TextView messageTitle = (TextView)view.findViewById(R.id.message_title);
        TextView messageContent = (TextView)view.findViewById(R.id.message_content);
        TextView unReadMessageCount = (TextView)view.findViewById(R.id.unread_message_count);
        TextView messageDate = (TextView)view.findViewById(R.id.message_date);

        messageIcon.setImageResource(R.drawable.ic_sys_message);
        messageTitle.setText(getString(R.string.label_title_sys_message));

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NaviUtils.gotoSysMessageList(getActivity());
            }
        });
        plistview.addHeaderView(view);
    }

    private BroadcastReceiver mBR = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent == null ||  intent.getAction() == null){
                return ;
            }
            String action = intent.getAction();
            if(SPUtils.BR_ACTION_SYNC_MESSAGE_OK.equals(action)){
                mList = DBManager.getInstance(getActivity()).getAllPrivateUsers();
                mAdapter.setData(mList);
            }
        }
    };
}
